package com.gxc.mall.goods.controller;

import com.google.common.collect.Maps;
import com.gxc.mall.goods.dto.UserEntity;
import com.gxc.mall.goods.dto.UserParam;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

/**
 * @author GongXincheng
 * @since 2019-09-03 15:41
 */
@RestController
public class HelloController {

    @Resource
    public DiscoveryClient discoveryClient;

    @GetMapping("/hello")
    public Object hello() {
        return "Hello World -> [cloud-mall-service-goods]";
    }

    @PostMapping("/json")
    public Map testJson(@RequestBody Map<Object, Object> map) {
        return map;
    }

    @GetMapping("/discovery")
    public Object discoveryClient() {
        Map<Object, Object> result = Maps.newHashMap();
        discoveryClient.getServices().forEach(serviceName ->
                discoveryClient.getInstances(serviceName).forEach(instance ->
                        result.put(serviceName, instance)
                )
        );
        return result;
    }

    @GetMapping("/test-with-pid")
    public UserEntity getWithPid() {
        UserEntity entity = new UserEntity();
        entity.setPzId("1");
        return entity;
    }

    @PostMapping("/test/v")
    public Object testV(@RequestBody @Valid UserParam param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return fieldError.getDefaultMessage();
            }
        }
        return param;
    }
}
